import React, { Component } from 'react';
import { View, Text, Platform, ScrollView, AlertIOS, RefreshControl, TextInput, Dimensions, KeyboardAvoidingView } from 'react-native';
import { List, Button, Modal, DatePicker, Toast, Picker, Flex } from 'antd-mobile-rn';
import Utils from '../../utils';
import { NavigationActions, StackActions } from 'react-navigation';
import moment from 'moment';
import ImagePicker from 'react-native-image-picker'; //第三方相机
import ImageCropPicker from 'react-native-image-crop-picker'
import userService from '../../service/userService';
import pickerPopup from '../../components/pickerPopup';
import cityPickerPopup from '../../components/cityPickerPopup';
import scorePopup from '../../components/scorePopup';
import TextAreaItem from 'antd-mobile-rn/lib/textarea-item/index.native';
import api from '../../utils/api';
import constants from '../../utils/constants';
import { BoxShadow } from 'react-native-shadow';
const screen = Dimensions.get("screen");
var photoOptions = {
    //底部弹出框选项
    title: '请选择',
    cancelButtonTitle: '取消',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '选择相册',
    quality: 0.75,
    allowsEditing: true,
    noData: false,
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
}

const Item = List.Item;

export default class UserTarget extends Component {


    state = {
        birth: new Date(),
        target: {
            targetScoreVo: {
                listening: 0,
                reading: 0,
                speaking: 0,
                writing: 0
            }
        },
        refreshing: true
    }


    _updateStorage = (user) => {
        const { navigation } = this.props;
        Utils.setStorage("LoginUserInfo", user).then(() => {
            this.setState({
                user: user
            });
            const back = navigation.getParam("back");
            if (back) {
                back(user);
            }
        }).catch((e) => {
            //Toast.info("e:"+e);

        })
    }

    constructor(props) {
        super(props)
        this.navigation = this.props.navigation;

    }

    loadData = () => {
        this.setState({
            refreshing: true
        })
        api({
            url: "/target/getInfo"
        }).then(data => {
            if (!data.success) {
                this.setState({
                    refreshing: false
                })
                return;
            }
            this.setState({
                target: data.result,
                refreshing: false
            })
        }).catch((data) => {
            this.setState({
                refreshing: false
            })
        })
    }

    componentDidMount() {

        this.loadData();





    }


    /**
     * 更新
     */
    updateTarget = (target) => {

        const stateTarget = this.state.target;

        for (let key in target) {
            stateTarget[key] = target[key];
        }

        this.setState({
            target: stateTarget
        })

        api({
            url: "/target/updateInfo",
            method: "POST",
            body: target
        }).then(data => {
            if (data.success) {

            }
        }).catch(() => {

        })

    }

    _updateUser = (key, value, user) => {
        const form = {
            [key]: value
        };


        userService.update(form).then(data => {
            if (data.success) {
                const u = data.result;

                user[key] = u[key];
                this._updateStorage(user);


            }
        })
    }
    selectScore = () => {
        const { target } = this.state;
        const targetScoreVo = target.targetScoreVo;
        scorePopup([targetScoreVo.listening, targetScoreVo.reading, targetScoreVo.speaking, targetScoreVo.writing], "目标分数").then(values => {
            const targetScore = values.reduce((x, y) => x + y);
            let score = targetScore > 0 ? targetScore / 4 : 0;
            score += "";
            const s = score.split(".");
            if (s.length == 2) {
                const s1 = s[1];
                if (s1 === "15") {
                    score = s[0];
                }
                if (s1 === "125") {
                    score = s[0];
                }
                if (s1 === "25") {
                    score = s[0] + ".5";
                }
                if (s1 === "375") {
                    score = s[0] + ".5";
                }
                if (s1 === "625") {
                    score = s[0] + ".5";
                }
                if (s1 === "75") {
                    score = parseInt(s[0]) + 1;
                }
                if (s1 === "875") {
                    score = parseInt(s[0]) + 1;
                }

            }

            this.updateTarget({
                targetScore: score,
                targetScoreVo: {
                    listening: values[0],
                    reading: values[1],
                    speaking: values[2],
                    writing: values[3]
                }
            });
        })
    }



    render() {

        console.log("ussser::", this.state);

        const { getParam, state, setParams } = this.navigation;

        const target = this.state.target;

        const user = {};



        return (

            <View style={{ flex: 1, backgroundColor: '#f5f5f9' }}>

               
                    <ScrollView
                        style={{ flex: 1, backgroundColor: '#f5f5f9' }}

                    // refreshControl={
                    //     <RefreshControl
                    //         colors={[constants.themeColor]}
                    //         refreshing={this.state.refreshing}
                    //         onRefresh={() => {
                    //             this.loadData();
                    //         }}
                    //         progressBackgroundColor="#fff"
                    //     />
                    // }
                    >
                        <View style={{ padding: 15 }}>

                            <BoxShadow setting={{
                                width: (screen.width - 30), //包裹的子内容多宽这里必须多宽
                                height: 495,//同上
                                border: 15,//阴影宽度
                                radius: 15,//包裹的子元素圆角多少这里必须是多少
                                opacity: 0.2,//透明度
                                x: 0,
                                y: 8,
                            }}>

                                <View style={{ height: 500, backgroundColor: "#fff", borderRadius: 15, overflow: "hidden" }} >

                                    <KeyboardAvoidingView  behavior={"position"} enabled keyboardVerticalOffset={50}> 
                                    <List style={{ borderTopWidth: 0 }} >

                                        <Item style={{ borderTopWidth: 0 }} onClick={() => {
                                            this.selectScore();


                                        }}>
                                            <View style={{ height: 65, alignContent: "center", alignItems: "center" }}>
                                                <View style={{ flexDirection: "row", alignItems: "center", alignContent: "center", marginTop: 15 }}>
                                                    <Text style={{ fontSize: 16, fontWeight: "bold", color: "#000", marginRight: 15 }}>目标分数</Text>
                                                    <Text style={{ fontSize: 24, fontWeight: "bold", color: "orange", marginLeft: 15 }}>
                                                        {target.targetScore ? target.targetScore : 0.0}
                                                    </Text>
                                                </View>

                                            </View>
                                        </Item>

                                        <Item onClick={() => {
                                            this.selectScore();
                                        }}>
                                            <Flex>
                                                <Flex.Item style={{ alignItems: "center" }}>
                                                    <Text>听力：{target.targetScoreVo.listening}</Text>
                                                </Flex.Item>
                                                <Flex.Item style={{ alignItems: "center" }}>
                                                    <Text>阅读：{target.targetScoreVo.reading}</Text>
                                                </Flex.Item>
                                                <Flex.Item style={{ alignItems: "center" }}>
                                                    <Text>写作：{target.targetScoreVo.writing}</Text>
                                                </Flex.Item>
                                                <Flex.Item style={{ alignItems: "center" }}>
                                                    <Text>口语：{target.targetScoreVo.speaking}</Text>
                                                </Flex.Item>
                                            </Flex>

                                        </Item>

                                        <Item arrow="horizontal" extra={target.enrollStatus == 1 ? "已报名" : "未报名"} onClick={() => {
                                            pickerPopup("报名状态", [{
                                                data: ["未报名", "已报名"].map((value, index) => { return { label: value, value: index } })
                                            }]).then(data => {
                                                this.updateTarget({
                                                    enrollStatus: data[0]
                                                })
                                            })

                                        }}>
                                            状态
                        </Item>
                                        <DatePicker
                                            format={"YYYY-MM-DD"}
                                            mode="date"
                                            minDate={new Date()}
                                            maxDate={new Date(2030, 1, 1)}

                                            extra={target.examDate ? (moment(target.examDate).format("YYYY-MM-DD")) : ""}
                                            onOk={(value) => {
                                                //console.log("date:val",moment(value).format("YYYY-MM-DD"));

                                                this.updateTarget({
                                                    examDate: value.getTime()
                                                })
                                            }}

                                        >
                                            <Item arrow="horizontal" extra={target.examDate ? target.examDate : ''}>
                                                考试时间
                        </Item>
                                        </DatePicker>
                                        <Item arrow="horizontal" extra={target.examAddress} onClick={() => {
                                            if (Platform.OS === 'ios') {
                                                AlertIOS.prompt("考试地点", "修改考试地点", [
                                                    { text: "取消" },
                                                    {
                                                        text: "确定", onPress: (value) => {
                                                            if (value) {
                                                                this.updateTarget({
                                                                    examAddress: value
                                                                })
                                                            }
                                                        }
                                                    }
                                                ])
                                                return;
                                            }
                                            Modal.prompt("考试地点", "修改考试地点", (value) => {

                                                if (value) {
                                                    this.updateTarget({
                                                        examAddress: value
                                                    })
                                                }

                                            })
                                        }}>
                                            考试地点
                        </Item>
                                        <Item arrow="horizontal" extra={target.examScore ? target.examScore : "0.0"} onClick={() => {

                                            const examScoreVo = target.examScoreVo;
                                            scorePopup([examScoreVo.listening, examScoreVo.reading, examScoreVo.speaking, examScoreVo.writing], "目前分数").then(values => {
                                                //const examScore = values.reduce((x, y) => x + y);
                                                const targetScore = values.reduce((x, y) => x + y);
                                                let score = targetScore > 0 ? targetScore / 4 : 0;
                                                score += "";
                                                const s = score.split(".");
                                                if (s.length == 2) {
                                                    const s1 = s[1];
                                                    if (s1 === "15") {
                                                        score = s[0];
                                                    }
                                                    if (s1 === "25") {
                                                        score = s[0] + ".5";
                                                    }
                                                    if (s1 === "375") {
                                                        score = s[0] + ".5";
                                                    }
                                                    if (s1 === "625") {
                                                        score = s[0] + ".5";
                                                    }
                                                    if (s1 === "75") {
                                                        score = parseInt(s[0]) + 1;
                                                    }
                                                    if (s1 === "875") {
                                                        score = parseInt(s[0]) + 1;
                                                    }

                                                }
                                                this.updateTarget({
                                                    examScore: score,
                                                    examScoreVo: {
                                                        listening: values[0],
                                                        reading: values[1],
                                                        speaking: values[2],
                                                        writing: values[3]
                                                    }
                                                });

                                            })


                                        }}>
                                            目前分数
                                        </Item>
                                        <Item >
                                            <View>
                                                <Text style={{ fontSize: 16, color: "#000", paddingTop: 5 }}>立个Flag</Text>
                                            </View>
                                            <View>
                                                <TextInput
                                                    returnKeyType={"done"}
                                                    onSubmitEditing={(e) => {
                                                        const text = e.nativeEvent.text;
                                                        this.updateTarget({
                                                            declaration: text
                                                        })
                                                    }}
                                                    onChange={e => {
                                                        const text = e.nativeEvent.text;
                                                        target.declaration = text;

                                                        this.setState({
                                                            target: target
                                                        })

                                                    }} placeholder={"考不到就不玩吃鸡"} value={target.declaration} style={{ height: 80, textAlign: "center", fontSize: 32 }}></TextInput>
                                            </View>
                                        </Item>

                                    </List>




                                    <View style={{ alignItems: "center", marginTop: 25 }}>
                                        <Button
                                            onClick={() => {
                                                this.props.navigation.navigate("UserPoster", { target: target })
                                            }}
                                            type={"primary"}
                                            activeStyle={{ backgroundColor: "orange", borderColor: "orange" }}
                                            style={{ width: 250, borderRadius: 15, backgroundColor: "orange", borderColor: "orange" }}
                                        >
                                            <Text style={{ fontSize: 24 }}> 生成Flag海报 </Text>
                                        </Button>
                                    </View>
                                    </KeyboardAvoidingView>

                                </View>
                            </BoxShadow>
                        </View>

                    </ScrollView>
              

            </View>
        )

    }
}